package com.yx.modules.api.controller;


import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.yx.common.utils.R;
import com.yx.common.validator.Assert;
import com.yx.modules.api.annotation.AuthIgnore;
import com.yx.modules.api.service.TbUserService;
import com.yx.utils.SmsDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 注册
 * Created by wuye on 2017/11/24.
 */
@RestController
@RequestMapping("/api")
public class ApiRegisterController {
    @Autowired
    private TbUserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 注册
     */
    @AuthIgnore
    @PostMapping("register")
    public R register(String mobile, String password, String code) {
        Assert.isBlank(mobile, "手机号不能为空");
        Assert.isBlank(password, "密码不能为空");
        Assert.isBlank(code, "验证码不能为空");
        //判断验证码是否正确
        String rcode = redisTemplate.opsForValue().get(mobile);
        if (rcode == null) {
            return R.error("验证码过期");
        }
        if (rcode.equals(code)) {
            if (userService.queryByMobile(mobile) == null) {

                //持久化数据
                userService.save(mobile, password);
                return R.ok();
            } else {
                return R.error("手机号已经被注册");
            }
        } else {
            return R.error("验证码错误");
        }
    }

    private static int captchaExpires = 60; //超时时间一分钟

    /**
     * 获取验证码
     */
    @AuthIgnore
    @GetMapping("/getCode")
    public R getCode(String phone) throws ClientException {
        //生成验证码
        String code = String.valueOf(new Random().nextInt(99999));
        //将验证码以<key,value>形式缓存到redis
        redisTemplate.opsForValue().set(phone, code);
        //设置过期时间
        redisTemplate.expire(phone, captchaExpires, TimeUnit.SECONDS);
        //调用第三方短信接口
        SendSmsResponse response = SmsDemo.sendSms(phone, Integer.valueOf(code));
        if ("isv.BUSINESS_LIMIT_CONTROL".equals(response.getCode())) {
            return R.error("一分钟内只能发一次");
        } else {
            return R.ok().put("response", response);
        }
    }
}

